// @flow
import React, { Component } from 'react'
import styles from './Customer.css'
import { Button, Form, Checkbox, Input  } from 'antd'
const Search = Input.Search
// import CustomerGrid from './CustomerGrid'
import CustomerGrid from './CustomerTable'
import universalFetch, { handleFetchError } from 'store/modules/fetch'
import { connect } from 'react-redux'
type Props = {
  userId: string,
  history: Object,
  form: Object,
  customersPermission: Array<any>, // 传过来的数组
  getCustomersPermission: Function
}
type States = {
  customers: Array<Object>, // 所有的客户信息
  rowData: Array<Object>, // 搜索后的客户信息
  total: number,
  current: number,
  pageSize: number,
  customersPermission: Object
}
class Customer extends Component {
  props: Props
  state: States
  queryUrl: String
  getCustomers: Function
  addCustomer: Function
  handleSearch: Function
  updataCustomersPermission: Function
  readALLChange: Function
  constructor (props: Props) {
    super(props)
    this.state = {
      customers: [],
      rowData: [],
      total: 0,
      current: 1,
      pageSize: 200000,
      customersPermission: {}
    }
    this.getCustomers = this.getCustomers.bind(this)
    this.addCustomer = this.addCustomer.bind(this)
    this.handleSearch = this.handleSearch.bind(this)
    this.updataCustomersPermission = this.updataCustomersPermission.bind(this)
    this.readALLChange = this.readALLChange.bind(this)
  }

  componentWillMount () {
    const { customersPermission } = this.props
    let obj = {}
    customersPermission.map((d, i) => {
      obj[d.id] = d
    })
    this.setState({
      customersPermission: obj
    })
  }

  componentDidMount () {
    this.getCustomers(this.state.current, this.state.pageSize)
  }

  updataCustomersPermission (data: Object) {
    const { customersPermission } = this.state
    // console.log('修改一项的结果--------');
    // console.log(data);
    this.setState({
      customersPermission: Object.assign({}, customersPermission, data)
    }, () => {
      this.props.getCustomersPermission(this.state.customersPermission)
    })
  }
  handleSearch (searchText) {
    const reg = new RegExp(searchText, 'gi')
    const { customers } = this.state
    this.setState({
      rowData: customers.map((record) => {
        let match = record.name.match(reg) // 搜索名字
        if (!match) {
          match = record.customerNo.match(reg) // 搜索编号
          if (!match) {
            match = record.industry.match(reg) // 搜索行业
            if (!match) {
              if (record.region.location) {
                match = record.region.location.match(reg) // 搜索地区
              }
              if (!match) {
                return false
              }
            }
          }
        }
        return {
          ...record
        }
      }).filter(record => !!record)
    })
  }
  getCustomers (page: number, pageSize: number) {
    let queryUrl = this.queryUrl || ``
    universalFetch(`${__SERVICE_API__}device/customers?userId=${this.props.userId}&pageNum=${page}&pageSize=${pageSize}${queryUrl}`)
      .then(res => res.json())
      .then((json) => {
        if (json.code !== 200000) {
          throw new Error(JSON.stringify({
            code: json.code,
            message: json.message
          }))
        }
        this.setState({
          current: page,
          total: json.pageInfo.total,
          customers: json.result,
          rowData: json.result
        })
      })
      .catch((error) => {
        handleFetchError(error)
        console.error(error)
      })
  }

  addCustomer () {
    this.props.history.push('/business/customer-add')
  }

  readALLChange (e, item) {
    const { customersPermission, customers } = this.state
    let obj = {}
    customers.map((d, i) => {
      obj[d.id] = { id: d.id, permission: [] }
    })
    obj = Object.assign({}, obj, customersPermission)
    let obj2 = {}
    if (e.target.checked) { // 全选
      let arr = Object.values(obj).map((d, i) => {
        const permission = d.permission
        if (permission.indexOf(item) === -1) {
          permission.push(item)
        }
        // 如果选中的是编辑或删除，查看也应该全选
        if (item !== 'readPermission' && permission.indexOf('readPermission') === -1) {
          permission.push('readPermission')
        }
        return d
      })
      arr.map((d, i) => {
        obj2[d.id] = d
      })
    } else { // 全不选
      let arr = []
      // 如果是查看的全不选就全部去掉, 如果不是查看的全不选就只操作自己的
      if (item !== 'readPermission') {
        arr = Object.values(obj).map((d, i) => {
          const permission = d.permission
          const index = permission.indexOf(item)
          if (index > -1) {
            permission.splice(index, 1)
          }
          return d
        })
      }
      arr.map((d, i) => {
        obj2[d.id] = d
      })
    }
    this.setState({
      customersPermission: obj2
    })

    this.props.getCustomersPermission(obj2) // 将变化的结果存到父元素中
  }

  render () {
    const component = this
    const { rowData, current, pageSize, total, customersPermission } = this.state
    return (
      <div className={styles['main']}>
        <div className={styles['action']}>
          {
            // <Button type='primary' onClick={this.addCustomer} style={{ marginTop: '6px' }}>添加客户</Button>
          }
          <p>
            选择该用户客户权限：
            <Search
              placeholder='输入关键字搜索'
              onSearch={this.handleSearch}
              style={{ width: 150 }}
            />
          </p>
          <p>
            全选：
            <Checkbox
              onChange={function (e) { component.readALLChange(e, 'readPermission') }}>查看</Checkbox>
            <Checkbox
              onChange={function (e) { component.readALLChange(e, 'editPermission') }}>编辑</Checkbox>
            <Checkbox
              onChange={function (e) { component.readALLChange(e, 'delPermission') }}>删除</Checkbox>
          </p>
        </div>
        <CustomerGrid {...{
          current,
          pageSize,
          total,
          customersPermission,
          refreshCustomers: this.updataCustomersPermission,
          rowData: rowData,
          history: this.props.history
        }} />
      </div>
    )
  }
}

const mapStatesToProps = (state) => {
  return {
    userId: state.user.userId
  }
}
export default connect(mapStatesToProps, {})(Form.create()(Customer))
